package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")
    private String picLocalPath;
    @Override
    public String savePicture(MultipartFile pic) {
        File file = new File(picLocalPath);
        if(!file.exists()) {
            file.mkdirs();
        }
        //获取文件名
        String fileName = pic.getOriginalFilename();
        assert (fileName != null);
        //获取文件名后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成随机数字以防图片名称重名
        fileName = UUID.randomUUID() + suffix;

        //上传图片到本地
        try {
            pic.transferTo(new File(picLocalPath + "/" + fileName));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PIC_UPLOAD_ERROR);
        }
        return fileName;
    }
}
